
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include <string>
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"InetAddr.hpp"
#include<functional>
#include"thread.hpp"

using namespace kzz;
  int _sockfd;
  InetAddr server;

//收取
void Recv()
{
    while(true)
    {
         char buffer[1024]={0};
         
        int s = recvfrom(_sockfd, &buffer, sizeof(buffer), 0, server.Addr(), &server.Len());
        if (s > 0)
        {
           // kzz::LOG(LogLevel::DBUGER) << "客户端收取返回值成功,服务器为" << server.Ip() << ' ' <<server.Port();
            std::cout << "服务器返回数据为： "<<buffer << std::endl;
        }
        memset(buffer,0,sizeof(buffer));
    }

}
//发送
void Send()
{
         std::string input;
    while(true)
    //std::cout << "Place Enter:" ;
    //while(std::getline(std::cin, input))
    //while( std::getline(std::cin >> std::ws, input))
     {
        ////向服务器发数据
        //std::string input;
        
        std::cout << "Place Enter:" ;
        std::getline(std::cin >> std::ws, input);
         if(input.empty()) {
        continue;
    }
       // std::getline(std::cin, input);
        //我知道是什么原因了，每次都冲缓冲区读数据，上次写的和这次写的折叠了

        int n=sendto(_sockfd, input.c_str(), input.size(), 0, server.Addr(), server.Len());
        //std::cout<<"发送成功"<<input.c_str()<<' '<<n<<std::endl;
        if(n<0)
        {
            kzz::LOG(LogLevel::ERROR)<<"send fail";
            exit(1);
        }
         //std::cout << "Place Enter:" ;
     
    }

}









// using namespace std;
int main(int argc, char **argv)
{
    ////在命令行传入服务器的IP和端口
    if (argc != 3)
    {
        kzz::LOG(LogLevel::ERROR) << "客户端参数传入错误";
        return 2;
    }
  
    std::string port=argv[2];
    std::string ip=argv[1];
 

   InetAddr _server(ip,stoi(port));
   server=_server;

    
   _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (_sockfd < 0)
    {
        kzz::LOG(LogLevel::ERROR) << "client创建套接字失败";
        exit(1);
    }

    kzz::LOG(LogLevel::ERROR) << "client socket success,sockfd:"<<_sockfd;
   kzz::Thread recv(Recv);
   kzz::Thread send(Send);
    
      recv.Start();
      send.Start();


      sleep(10);
      recv.Join();
      send.Join();
    return 0;
}